import hashlib
import os
import sys
from datetime import datetime

import pandas as pd
import requests
from string import Template
import cProfile
from mongo.MongoHelper import MongoHelper
import logging
from logging.config import fileConfig
import configparser
import captcha
from PIL import Image

cfgdir = os.path.split(os.path.realpath(__file__))[0]
paths = cfgdir.split("/")
a = len(paths)-2
separator = '/'
arr = paths[1:a]
b = '/'+separator.join(arr)+'/'
cfg = os.path.join(cfgdir,'logging_config.ini')
fileConfig(b+"logging_config.ini", disable_existing_loggers=False)
logger = logging.getLogger('simple_example')
mongoHelper = None
config = configparser.ConfigParser()
cfgdir = os.path.split(os.path.realpath(__file__))[0]
# print(os.getcwd())
# print(os.path.abspath(__file__))
#print(os.path.basename(__file__))

os.path.dirname(os.path.basename(__file__))
cfg = os.path.join(os.getcwd(), 'config.cfg')
if len(sys.argv) >=2:
    config.read(sys.argv[1])
else:
    print(sys.argv)
    config.read(cfg)
database = config.get('db', 'database')
myUrl = config.get('db', 'url')
mongoHelper = MongoHelper(url=myUrl, database=database)
# 更新股票的二级市场信息
def equity_list():
    api = 'http://api.mairui.club/hslt/list/b53092223f1f8667e'
    params = {}
    r = requests.get(api, params=params)
    data_json = r.json()
    # dm:股票代码 mc 简称 jys 股票市场
    print(data_json)
    # temp_df = pd.DataFrame(data_json["result"]["data"])
    for rec in data_json:
        if mongoHelper:
            coll = mongoHelper.mongo_db.get_collection('equityBasic')
            qCon = {'code': rec['dm']}
            result = coll.find_one(qCon)
            # print(result)
            if result and result['exchange']:
                print(result)
            elif result and not result['exchange']:
                # 更新操作：更新单个文档中的字段
                filter_condition = {'code': rec['dm']}  # 用于找到需要更新的文档的条件
                update_operation = {'$set': {'exchange': rec['jys']}}  # 更新操作，使用$set来指定新值
                u = coll.update_one(filter_condition,update_operation)
                print('find it')
                print(u.matched_count, u.modified_count)
            else: #
                record = {"code": rec['dm'], "createdTime": datetime.now(),'source': 'MA', 'exchange': rec['jys']}
                i = coll.insert_one(record)
                if i is None:
                    print(f"{rec['dm']}基本信息入库失败")
                else:
                    print(f"{rec['dm']}基本信息入库成功{i.inserted_id}")
        else:
            print('db is not available')
def financesecurities(code=''):
    api = f'http://api.mairui.club/hsrq/lszs/{code}/b53092223f1f8667e'
    params = {}
    r = requests.get(api, params=params)
    data_json = r.json()
    print(data_json)
    for rec in data_json:
        if mongoHelper:
            coll = mongoHelper.mongo_db.get_collection('marginHis')
            qCon = {'rq': rec['rq'],'code':code}
            result = coll.find_one(qCon)
            if result is None:
                rec.update({'code':code})
                result = coll.insert_one(rec)
                if result is not None:
                    print('Added')
                else:
                    print('not added')
            else:
                a = 1
        else:
            print('db is not available')



# 主力连续净流出
def outcashflow():
    api = 'http://api.mairui.club/hizj/lxlc/b53092223f1f8667e'
    params = {}
    r = requests.get(api, params=params)
    data_json = r.json()
    print(data_json)

# 主力连续净流入
def incashflow():
    api = 'http://api.mairui.club/hizj/lxlr/b53092223f1f8667e'
    params = {}
    r = requests.get(api, params=params)
    data_json = r.json()
    print(data_json)

if __name__ == "__main__":
    print("--------------------------------")
    print(sys.argv)
    print("--------------------------------")
    config = configparser.ConfigParser()
    if len(sys.argv) >=2:
        config.read(sys.argv[1])
    else:
        config.read('../../config.cfg')
    database = config.get('db', 'database')
    myUrl = config.get('db', 'url')
    mongoHelper = MongoHelper(url=myUrl, database=database)
    equity_list()
    # financesecurities(code='600487')
    # outcashflow()
    # incashflow()
    # cProfile.run('equitylist()')

    m = hashlib.md5()
    m.update(b"password")
    print(m.digest_size)
    print(m.digest())
    print(m.hexdigest())

    m = hashlib.md5()
    p = 'password'
    m.update(p.encode("utf-8"))
    print(m.digest_size)
    print(m.digest())
    print(m.hexdigest())

    # 生成验证码文本和图片
    captcha_text, image = captcha.generate_captcha()

    # 将图片保存到文件
    image.save('captcha.png')

    # 打印生成的验证码文本
    print(captcha_text)

